package com.lj.infoisland.job.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Set;

/*
 * @description 小岛热榜定时任务
 * @author 龙洁
 * @create 2024-11-02 下午12:20
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class IslandHotSearchJob {

    private final StringRedisTemplate redisTemplate;

    public static final String HOT_KEY = "news_hot_info_island_";

    @XxlJob("IslandHotSearchJob")
    public ReturnT<String> hotSearch(String param) {
        log.info("小岛热榜定时任务开始");
        try {
            // 获取当前日期
            LocalDate today = LocalDate.now();
            // 获取前一天的日期
            LocalDate yesterday = today.minusDays(1);

            // 创建一个DateTimeFormatter对象，用于格式化日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 格式化今天的日期
            String formattedTodayKey = HOT_KEY+today.format(formatter);
            // 格式化昨天的日期
            String formattedYesterdayKey = HOT_KEY+yesterday.format(formatter);
            // 拿到昨天zSet中的数据，并更新到今天的zSet中变为1/10
            Set<String> yesterdayArticles = redisTemplate.opsForZSet().range(formattedYesterdayKey, 0, -1);
            if (yesterdayArticles != null) {
                for (String item : yesterdayArticles) {
                    Double score = redisTemplate.opsForZSet().score(formattedYesterdayKey, item);
                    if (score != null) {
                        // 计算新的分数
                        double newScore = score * 0.1;
                        // 将成员及其新分数添加到有序集合中
                        redisTemplate.opsForZSet().add(formattedTodayKey, item, newScore);
                    }
                }
            }
            System.out.println("小岛热榜定时任务执行完毕");
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
